﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Exchange.WebServices.Data;
using System.Net;

namespace DeployForwardMailboxRules.Service
{
	class ExchangeOnPremise : ExchangeServiceBase
	{
		private string _userName;
		//ToDo: Use SecureString.
		private string _password;
		private string _domainName;
		private string _ewsEndpoint;
		private bool _useAutoDiscover;

		/// <summary>
		/// Ctor
		/// </summary>
		/// <param name="userName"></param>
		/// <param name="password"></param>
		/// <param name="domainName"></param>
		/// <param name="ewsEndpoint"></param>
		/// <param name="useAutoDiscover"></param>
		public ExchangeOnPremise(string userName, string password, string domainName, string ewsEndpoint, bool useAutoDiscover)
		{
			_userName = userName;
			_password = password;
			_domainName = domainName;
			_ewsEndpoint = ewsEndpoint;
			_useAutoDiscover = useAutoDiscover;
		}

		private ExchangeService _exchService;
		protected override ExchangeService ExchService
		{
			get 
			{
				if (_exchService == null)
				{
					_exchService = GetService();
				}
				return _exchService;
			}
		}

		/// <summary>
		/// Get ExchangeService object.
		/// </summary>
		/// <returns></returns>
		private ExchangeService GetService()
		{
			ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
			service.Credentials = new NetworkCredential(_userName, _password, _domainName);

			if (_useAutoDiscover)
			{
				service.AutodiscoverUrl(_userName, delegate(string address) { return true; });
			}
			else
			{
				service.Url = new Uri(_ewsEndpoint);
			}
			return service;
		}
	}
}
